package org.softmed.rest.server.xstream;

import java.util.HashMap;
import java.util.Map;

import org.softmed.persistence.PersistenceManager;
import org.softmed.rest.config.Application;

public class XMLCache {

	static Map<String, DefaultToXMLHideNonNativeConverter> normalConverters = new HashMap<String, DefaultToXMLHideNonNativeConverter>();
	static Map<String, DefaultToXMLListItemConverter> listConverters = new HashMap<String, DefaultToXMLListItemConverter>();
	static Map<String, CustomDefaultXMLUnmarshaller> unmarshallers = new HashMap<String, CustomDefaultXMLUnmarshaller>();

	public static void reset() {
		normalConverters.clear();
		listConverters.clear();
		unmarshallers.clear();
	}

	public static DefaultToXMLHideNonNativeConverter getNormalConverter(
			Class type, PersistenceManager odbUtil, Application app,
			Object... options) throws Throwable {
		DefaultToXMLHideNonNativeConverter conv = normalConverters.get(type
				.getCanonicalName());
		if (conv != null) {
			conv.setNonDetailed();

			if (options != null && options.length > 0) {
				String detail = (String) options[0];
				if (detail.equals("detailed")) {
					conv.setDetailed();
				}
			}

			return conv;
		}

		conv = new DefaultToXMLHideNonNativeConverter();
		conv.setup(type, odbUtil, app, options);

		normalConverters.put(type.getCanonicalName(), conv);

		return conv;

	}

	public static DefaultToXMLListItemConverter getListConverter(Class type,
			PersistenceManager odbUtil, Application app, Object... options)
			throws Throwable {
		DefaultToXMLListItemConverter conv = listConverters.get(type
				.getCanonicalName());
		if (conv != null)
			return conv;

		conv = new DefaultToXMLListItemConverter();
		conv.setup(type, odbUtil, app, options);

		listConverters.put(type.getCanonicalName(), conv);

		return conv;

	}

	public static CustomDefaultXMLUnmarshaller getUnmarshaller(Class type,
			PersistenceManager odbUtil, Application app) throws Throwable {
		CustomDefaultXMLUnmarshaller conv = unmarshallers.get(type
				.getCanonicalName());
		if (conv != null)
			return conv;

		conv = new CustomDefaultXMLUnmarshaller(odbUtil, type, app);
		// conv.setup(type, odbUtil, app, options);

		unmarshallers.put(type.getCanonicalName(), conv);

		return conv;

	}

}
